document.addEventListener('DOMContentLoaded', function () {
  const resumeData = JSON.parse(localStorage.getItem('resumeData'));
  const formContainer = document.querySelector('.form-container');
  const btnContainer = document.getElementById('button-container');
  const field = document.getElementById('field');

  if (resumeData) {
    try {
      const content = resumeData.content;
      if (typeof content === 'string' && (content.startsWith('http://') || content.startsWith('https://'))) {
        if (formContainer) {
          formContainer.style.display = 'none';
        }
        if (field) {
          field.innerHTML = '';
          const combinedContainer = document.createElement('div');
          combinedContainer.className = 'download-link-container';
          const linkContainer = document.createElement('div');
          linkContainer.className = 'resume-link';

          const link = document.createElement('a');
          link.href = content;
          link.textContent = '点击下载简历';
          link.target = '_blank';
          link.className = 'download-link';

          linkContainer.appendChild(link);
          combinedContainer.appendChild(linkContainer);
          if (btnContainer) {
            btnContainer.parentNode.removeChild(btnContainer);
            combinedContainer.appendChild(btnContainer);
          }
          field.appendChild(combinedContainer);
        }
      } else {
        const contentObj = JSON.parse(content);
        const form = document.getElementById('userForm');
        if (form) {
          for (const key in contentObj) {
            const input = form.querySelector(`[name="${key}"]`);
            if (input) {
              if (input.type === 'radio') {
                const radio = form.querySelector(`[name="${key}"][value="${contentObj[key]}"]`);
                if (radio) radio.checked = true;
              } else if (input.tagName === 'SELECT') {
                const option = input.querySelector(`option[value="${contentObj[key]}"]`);
                if (option) option.selected = true;
              } else {
                input.value = contentObj[key];
              }
              input.readOnly = true;
              input.style.border = '1px solid #ccc';
              input.style.padding = '5px';
            }
          }
        }
      }
    } catch (error) {
      console.error('解析简历数据时出错:', error);
      alert('解析简历数据时出错，请检查数据格式');
    }
  }
});

var editResumeBtn = document.getElementById('editResumeBtn');
var deleteResumeBtn = document.getElementById('deleteResumeBtn');
var updateResumeBtn = document.getElementById('updateResume');

function deleteResume() {
  const usersId = localStorage.getItem('userId');
  if (!usersId) {
    alert('未获取到简历ID，请重新登录或检查数据');
    return;
  }
  if (confirm('确定要删除这份简历吗？')) {
    const resumeData = JSON.parse(localStorage.getItem('resumeData'));
    const id = resumeData ? resumeData.id : null;
    if (!id) {
      alert('未获取到简历ID，请重新登录或检查数据');
      return;
    }
    const url = `http://192.168.244.14:8080/resumeStatus/delete/${id}&${usersId}`;

    fetch(url, {
      method: 'DELETE'
    })
      .then(response => {
        if (!response.ok) {
          throw new Error('网络响应错误：' + response.status);
        }
        return response.json();
      })
      .then(data => {
        if (data && data.code === 1) {
          alert('简历删除成功');
          window.location.href = "http://127.0.0.1:5501/sparkResume/html/users-function1.html";
        } else {
          alert('删除失败：' + (data && data.msg ? data.msg : '未知错误'));
        }
      })
      .catch(error => {
        console.error('删除请求出错:', error);
        alert('删除请求出错，请检查网络连接');
      });
  }
}

document.addEventListener('DOMContentLoaded', function () {
  const approveResumeBtn = document.getElementById('approveResumeBtn');
  if (approveResumeBtn) {
    approveResumeBtn.addEventListener('click', function () {
      const resumeData = JSON.parse(localStorage.getItem('resumeData'));
      const id = resumeData ? resumeData.id : null;
      const usersId = resumeData ? resumeData.usersId : null;
      if (!id || !usersId) {
        alert('未获取到简历ID或用户ID，请重新登录或检查数据');
        return;
      }
      if (confirm('确定要通过这份简历吗？')) {
        fetch(`http://192.168.244.14:8080/resumeStatus/approve?id=${id}&usersId=${usersId}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          }
        })
          .then(response => {
            if (!response.ok) {
              throw new Error('网络响应错误：' + response.status);
            }
            return response.json();
          })
          .then(data => {
            console.log('后端返回的数据:', data);
            if (data && data.code === 1) {
              alert('简历已通过');
              window.location.href = "http://127.0.0.1:5501/sparkResume/html/manager-function.html";
            } else {
              alert('修改失败：' + (data && data.msg ? data.msg : '未知错误'));
            }
          })
          .catch(error => {
            console.error('修改简历状态请求出错:', error);
            alert('修改简历状态请求出错，请检查网络连接');
          });
      }
    });
  }

  const disapproveResumeBtn = document.getElementById('disapproveResumeBtn');
  if (disapproveResumeBtn) {
    disapproveResumeBtn.addEventListener('click', function () {
      const resumeData = JSON.parse(localStorage.getItem('resumeData'));
      const id = resumeData ? resumeData.id : null;
      const usersId = resumeData ? resumeData.usersId : null;
      if (!id || !usersId) {
        alert('未获取到简历ID或用户ID，请重新登录或检查数据');
        return;
      }
      if (confirm('确定不通过这份简历吗？')) {
        fetch(`http://192.168.244.14:8080/resumeStatus/disapprove?id=${id}&usersId=${usersId}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          }
        })
          .then(response => {
            if (!response.ok) {
              throw new Error('网络响应错误：' + response.status);
            }
            return response.json();
          })
          .then(data => {
            if (data && data.code === 1) {
              alert('简历不通过');
              window.location.href = "http://127.0.0.1:5501/sparkResume/html/manager-function.html";
            } else {
              alert('修改失败：' + (data && data.msg ? data.msg : '未知错误'));
            }
          })
          .catch(error => {
            console.error('修改简历状态请求出错:', error);
            alert('修改简历状态请求出错，请检查网络连接');
          });
      }
    });
  }
});

document.addEventListener('DOMContentLoaded', function () {
  const editCommentBtn = document.getElementById('editComment');
  if (editCommentBtn) {
    editCommentBtn.addEventListener('click', function () {
      const resumeData = JSON.parse(localStorage.getItem('resumeData'));
      const userId = resumeData ? resumeData.usersId : null;
      if (!userId) {
        alert('未获取到用户 ID，请重新查看简历');
        return;
      }
      fetch(`http://192.168.244.14:8080/comment/select/${userId}`, {
        method: 'GET',
        headers: {
          'Accept': 'application/json'
        }
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('网络响应错误：' + response.status);
          }
          return response.json();
        })
        .then(data => {
          console.log('后端返回的留言数据:', data);
          if (data && data.code === 1) {
            const comment = data.data.comment || '';
            let statusText;
            switch (parseInt(resumeData.status)) {
              case 1:
                statusText = '已投递';
                break;
              case 2:
                statusText = '已查看';
                break;
              case 3:
                statusText = '已通过';
                break;
              case 4:
                statusText = '未通过';
                break;
              default:
                statusText = '未知状态';
            }
            const name = resumeData.name;
            const url = `http://127.0.0.1:5501/sparkResume/html/Comment.html?userId=${userId}&name=${name}&status=${statusText}&comment=${encodeURIComponent(comment)}`;
            window.location.href = url;
          } else {
            alert('查询留言失败：' + (data && data.msg ? data.msg : '未知错误'));
          }
        })
        .catch(error => {
          console.error('查询留言请求出错:', error);
          alert('查询留言请求出错，请检查网络连接');
        });
    });
  }
});